package com.ruoyi.system.utils;

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

import static com.ruoyi.common.utils.ServletUtils.urlDecode;

@Component
@Slf4j
public class FileDataUtils {

    /**
     * 创建文件:
     */
    public static File createFile(String fileName, String content){
        String path = getProjectRootPath();
        File file = new File(path+fileName);
        if(!file.exists()){
            // 文件不存在创建文件
            try {
                FileUtils.write(file, content, "UTF-8");
            } catch (IOException e) {
                log.error("创建文件失败:{}",e.getMessage());
                throw new ServiceException("文件创建失败：" + e.getMessage());
            }
        }

        return file;
    }

    /**
     * 创建文件:
     */
    public static File removeFile(String fileName){
        String path = getProjectRootPath();
        File file = new File(path+fileName);
        if(file.exists()){
            FileUtils.deleteQuietly(file);
        }

        return file;
    }

    /**
     * 获取文件路径
     * @throws
     */
    public static String getProjectRootPath(){
        String url = null;
        try {
            url = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            log.error("获取项目根目录失败:{}",e.getMessage());
        }
        return urlDecode(new File(url).getAbsolutePath()) + File.separator + "static" + File.separator;
    }

    /**
     * 读取python，生成csv文件，并读取数据
     * @param path
     * @param dataSize
     * @param fileName
     * @return
     */
    public static List<String> generateData(String path,String max,String min,String dataSize) {
        List<String> resultList = null;
        String tempName = getProjectRootPath() + UUID.randomUUID()+".csv";
        try {
            String[] command = {"python", path, max, min ,dataSize,tempName};
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                log.info(line);
            }

            // 读取csv文件
            resultList = readCsv(tempName);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException(ExceptionUtil.getExceptionMessage(e));
        }
        return resultList;
    }

    /**
     * 读取csv数据
     * @param csvPath
     * @return
     */
    public static List<String> readCsv(String csvPath) {
        List<String> list = new ArrayList<>();
        CSVReader reader = null;
        try {
            reader = new CSVReader(new FileReader(csvPath));
            String[] data;
            reader.readNext(); // 跳过第一行数据
            while ((data = reader.readNext()) != null) {
                for (String result : data) {
                    list.add((int)Math.floor(Double.parseDouble(result)) + "");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (CsvValidationException e) {
            throw new RuntimeException(e);
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                    FileUtils.deleteQuietly(new File(csvPath)); // 删除临时文件
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    /**
     * python爬虫数据
     * @param path
     * @return
     */
    public static Map<String,List<String>> generateCollectData(String path) {
        Map<String,List<String>> resultList = null;
        String tempName = getProjectRootPath() + UUID.randomUUID()+".csv";
        try {
            String[] command = {"python", path,tempName};
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                log.info(line);
            }

            // 读取csv文件
            resultList = readCollectCsv(tempName);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException(ExceptionUtil.getExceptionMessage(e));
        }
        return resultList;
    }

    /**
     * 读取csv数据
     * @param csvPath
     * @return
     */
    public static Map<String,List<String>> readCollectCsv(String csvPath) {
        Map<String,List<String>> maplist = new HashMap<>();
        CSVReader reader = null;
        try {
            reader = new CSVReader(new InputStreamReader(Files.newInputStream(Paths.get(csvPath)), StandardCharsets.UTF_8));
            String[] data;
            String[] titleList = reader.readNext();
            for (String filedcnName : titleList) {
                maplist.put(filedcnName,new ArrayList<String>());
            }
            while ((data = reader.readNext()) != null) {
                List<String> newList = Arrays.asList(data);
                for (int i = 0; i < titleList.length; i++) {
                    maplist.get(titleList[i]).add(newList.get(i));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (CsvValidationException e) {
            throw new RuntimeException(e);
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                    FileUtils.deleteQuietly(new File(csvPath)); // 删除临时文件
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return maplist;
    }
}
